package com.king.juc.atomicdemo.account;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

/**
 * 保护共享资源演示案例
 * 模拟多线程取款操作
 *
 * @author king
 * @date 2020/11/29 16:47
 */
public interface DecimalAccount {

    /**
     * 获取余额
     */
    BigDecimal getBalance();

    /**
     * 取款
     */
    void withdraw(BigDecimal amount);

    /**
     * 方法内启动1000个线程, 每个线程做 -10 操作
     * 如果初始余额为10000, 那么正确结果应该为0
     */
    static void demo(DecimalAccount account) {
        List<Thread> list = new ArrayList<>();
        for (int i = 0; i < 1000; i++) {
            list.add(new Thread(() -> {
                account.withdraw(BigDecimal.TEN);
            }));
        }

        long start = System.currentTimeMillis();
        list.forEach(Thread::start);
        list.forEach(t -> {
            try {
                t.join();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        });

        System.out.println("account: " + account.getBalance() + " ms: " + (System.currentTimeMillis() - start));
    }
}
